package com.kfm.base.structure;

public class MyQueue extends Queue {

    // 存元素
    private Object[] value;

    // 下一个元素的下标 = 元素的个数
    private int size;

    // 默认长度
    private static final int DEFAULT_CAPACITY = 10;

    public MyQueue() {
        this(DEFAULT_CAPACITY);
    }

    public MyQueue(int capacity) {
        if (capacity < 0) {
            capacity = DEFAULT_CAPACITY;
        }
        value = new Object[capacity];
    }

    @Override
    void push(Object element) {
        if (size + 1 > value.length) {
            grow(); // 扩容
        }
        value[size] = element;
        size++;
    }

    private void grow() {
        int old = value.length;
//        int newCapacity = old + old >> 1;
        int newCapacity = old + 10; // 定长

        if (newCapacity <= old) {
            newCapacity = Integer.MAX_VALUE;
        }

//        value = Arrays.copyOf(value, newCapacity);

        // 使用 System.arraycopy
        Object[] newArr = new Object[newCapacity];
        System.arraycopy(value, 0, newArr, 0, size);

        value = newArr;
    }

    @Override
    Object pop() {
        Object element = value[0];
        System.arraycopy(value, 1, value, 0, size - 1);

        value[size - 1] = null; // 置 null
        size --;

        return element;
    }

    @Override
    Object peek() {
        return value[0];
    }

    @Override
    boolean isEmpty() {
        return size == 0;
    }

    @Override
    int size() {
        return size;
    }
}
